package repository

import (
	"context"
	"gitee.com/perception-network/block-chain-released/internal/model"
	"github.com/Ankr-network/kit/rdb"
)

const (
	userFields = "`id`, `name`, `version`, `create_time`"
	addFields  = "`name`, `version`"
	addOneSql  = "insert into `" + BLOCKCHAINTABLE + "` (" + addFields + ") values(?,?)"
	getDataSql = "select " + userFields + " from `" + BLOCKCHAINTABLE + "`"
)

type BlockChain interface {
	AddOne(ctx context.Context, info *model.Release) error
	GetData(ctx context.Context) ([]*model.Release, error)
}

type blockChainImpl struct {
	repo rdb.Repository
}

func NewBlockChain(repo rdb.Repository) *blockChainImpl {
	return &blockChainImpl{
		repo: repo,
	}
}

func (b *blockChainImpl) AddOne(ctx context.Context, info *model.Release) error {
	_, err := b.repo.AddOne(ctx, addOneSql, info.Name, info.Version)
	return err
}

func (b *blockChainImpl) GetData(ctx context.Context) ([]*model.Release, error) {
	var data []*model.Release
	err := b.repo.FindAll(ctx, &data, getDataSql)
	if err != nil {
		return nil, err
	}
	return data, nil
}
